/*****************************************************************************/
var sid_items="1234567890qwertyuiopasdfghjklzxcvbnm";
function mk_sid() {
	var r="";
	for (var i=0;i<48;i++) {
		r+=sid_items.substr(Math.floor(Math.random()*sid_items.length),1);
	}
	return r;
}
exports.mk_sid=mk_sid;

/*****************************************************************************/
function load_roles(space)
{
	if (space.user.no_roles==1) return;
	space.site.sql.execute_and_fetch("sessions/roles",{user_id:space.uid}).forEach(function(x) {
		space.roles[x.code]=1;
		space.role_ids[x.id]=1;
	});
}

/*****************************************************************************/
exports.auth=function(space) {
	var sql=space.site.sql;
	var query=space.fields;
	if (query['do-login']) {
		var r=sql.execute_and_fetch_one('sessions/auth_user',query);
		if (!r) return "no_user";
		space.uid=r.id;
		space.user=sql.execute_and_fetch_one('sessions/get_user',{user_id:r.id});
		var sid=mk_sid();
		sql.execute('sessions/insert',{sid: sid,user_id:r.id});
		var exp=undefined;
		var exprule=space.site.auth?space.site.auth.expires:undefined;
		var expdays=1;
		if (exprule) {
			switch (exprule.type) {
				case "days_plus":
					exp=new Date(new Date().getTime() + exprule.value*24*60*60*1000);
					expdays=Math.floor(exprule.value/5);
					break;
			}
		}
		space.res.cookie("sid",sid,exp,'/',space.site.cookie_domain);
		load_roles(space);
		if (space.site.auth && space.site.auth.onauth) space.site.auth.onauth.forEach(function(x) {space.functions[x](space);});
		sql.execute('sessions/delete_old',{days: expdays});
		return null;

	} else if (query['do-logoff']) {
		space.res.cookie("sid",'',undefined,'/',space.site.cookie_domain);
		return null;
	}
	var sid=space.req.cookie.sid;
	if (!sid) sid=space.fields.sid;
	if (!sid && space.req.get) sid=space.req.get.sid;
	if (!sid) return undefined;
	space.user=sql.execute_and_fetch_one('sessions/get_user_by_session',{sid: sid});
	if (!space.user) return "Wrong cookie";
	if (space.user.date_last_page_needs_update) sql.execute('sessions/update_date_last_page',space.user);
	if (space.user.date_exp_needs_update) sql.execute('sessions/update_date_exp',space.user);
	sql.commit();
	space.uid=space.user.id;
	load_roles(space);
	return undefined;
}

/*****************************************************************************/
